import { defineStore } from 'pinia'
import { useIdle } from '@vueuse/core'
import { LOGIN_NAME } from '@/const/router'
import { IS_LOCK, LOCK_PWD } from '@/const/storage'
import { getStorage, setStorage } from '@/app/storage'
import { LOCK_SCREEN_STORE_NAME } from '../const'

const dftLockTime = 60 * 60 * 1000

export default defineStore(LOCK_SCREEN_STORE_NAME, () => {
  const route = useRoute()
  const { idle } = useIdle(dftLockTime)

  const isLock = ref(getStorage(IS_LOCK) || false)
  const loginPwd = ref('123')
  const lockPwd = ref(getStorage(LOCK_PWD) || '')

  function setLock(val) {
    console.log(val)
    isLock.value = val
    setStorage(IS_LOCK, val)
    !val && resetLockPwd()
  }

  function setLockPwd(pwd) {
    setStorage(LOCK_PWD, pwd)
    lockPwd.value = pwd ? pwd : loginPwd.value
  }

  function saveLoginPwd(pwd) {
    loginPwd.value = pwd
  }

  function resetLockPwd() {
    setStorage(LOCK_PWD, '')
    lockPwd.value = ''
  }

  function verifyLockPwd(pwd) {
    return [lockPwd, loginPwd].some((n) => n.value === pwd)
  }

  window.addEventListener('beforeunload', () => {
    if (isLock.value && !lockPwd.value) {
      setLock(false)
    }
  })

  watch(idle, (idleValue) => {
    if (route.name === LOGIN_NAME) {
      setLock(false)
      return
    }

    if (idleValue) {
      setLock(true)
      setLockPwd()
    }
  })

  return {
    isLock,
    lockPwd,
    loginPwd,
    setLock,
    setLockPwd,
    verifyLockPwd,
    saveLoginPwd,
    resetLockPwd,
  }
})
